class cloud {
  constructor(options) {
    options = options || {};
    for (let key in options.cloud) {
      this[key] = options.cloud[key];
    }
    this.parent = options.that;
    this.ajax = this._ajax;
  }


  // 统一处理页面的请求
  async _ajax(options = {}, serviceType = this.parent.config.serviceType, errCatch = this.parent.config.errCatch) {
    const { path = '', method = 'GET', params = {}, body = {}, headers = { 'content-type': "application/json" }, exts = {}, name = '', data = {}, handler = 'main' } = options;
    return new Promise(async (resolve, reject) => {
      if (serviceType === 'cloud_fun') {
        if (!name) {
          reject('name need!');
        }
        try {
          const res = await this.function.invoke(name, data, handler, exts);
          resolve(res);
        } catch (err) {
          if (errCatch) {
            this.parent.launchErrPage(404, `云函数:${name},方法:${handler},调用异常.${JSON.stringify(err)}`);
          } else {
            reject(err);
          }
        }
      } else if (serviceType === 'cloud_app') {
        if (!path) {
          reject('path need!');
        }
        try {
          const res = await this.application.httpRequest({
            path,
            method,
            headers,
            params,
            body,
            exts,
          });
          resolve(res);
        } catch (err) {
          if (errCatch) {
            this.parent.launchErrPage(404, `云应用:${path},调用异常.${JSON.stringify(err)}`);
          } else {
            reject(err);
          }
        }
      } else {
        reject('cloud service abnormal');
      }
    });
  }
}
export default cloud;